<template>
	<view class="cart-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">购物车</text>
		</view>

		<!-- 购物车内容 -->
		<scroll-view class="cart-content" scroll-y="true" v-if="cartItems.length > 0">
			<!-- 收货地址 -->
			<view class="address-section" @click="showAddressPopup">
				<view class="address-info" v-if="selectedAddress">
					<text class="label">收货地址：</text>
					<text class="address">{{ selectedAddress }}</text>
				</view>
				<view class="address-placeholder" v-else>
					<text>请选择收货地址</text>
				</view>
				<text class="arrow">›</text>
			</view>

			<!-- 菜品列表 -->
			<view class="dish-list">
				<view v-for="(item, index) in cartItems" :key="index" class="cart-item">
					<image :src="item.image || '/static/default-dish.png'" mode="aspectFill" class="item-image"></image>
					<view class="item-info">
						<text class="item-name">{{ item.name }}</text>
						<text class="item-desc" v-if="item.description">{{ item.description }}</text>
						<view class="item-bottom">
							<text class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</text>
							<view class="cart-control">
								<text class="control-btn minus" @click="decrease(item)"
									:class="{ disabled: item.quantity === 1 }">-</text>
								<text class="quantity">{{ item.quantity }}</text>
								<text class="control-btn plus" @click="increase(item)">+</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 订单汇总 -->
			<view class="order-summary">
				<view class="summary-item">
					<text class="summary-label">商品总数</text>
					<text class="summary-value">{{ totalQuantity }}件</text>
				</view>
				<view class="summary-item">
					<text class="summary-label">商品总价</text>
					<text class="summary-value">¥{{ totalPrice.toFixed(2) }}</text>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="notes-section">
				<text class="section-title">备注信息</text>
				<textarea class="notes-input" v-model="notes" placeholder="请输入备注信息（可选）" maxlength="100"></textarea>
			</view>
		</scroll-view>

		<!-- 空购物车提示 -->
		<view class="empty-cart" v-else>
			<image src="/static/tabbar/cart.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">购物车空空如也</text>
			<view class="go-shopping" @click="goToClassify">
				<text>去选购</text>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="checkout-bar" v-if="cartItems.length > 0">
			<view class="total-info">
				<text class="total-label">合计：</text>
				<text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			<view class="checkout-btn" @click="checkLoginBeforeSubmit">
				<text>提交订单</text>
			</view>
		</view>

		<!-- 地址选择弹窗 -->
		<view class="address-popup" v-if="showAddressDialog">
			<view class="popup-mask" @click="closeAddressPopup"></view>
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">选择收货地址</text>
					<text class="popup-close" @click="closeAddressPopup">×</text>
				</view>
				<view class="address-input-section">
					<textarea class="address-input" v-model="addressInput" placeholder="请输入详细收货地址" maxlength="100"
						auto-height></textarea>
				</view>
				<view class="popup-buttons">
					<view class="popup-btn cancel" @click="closeAddressPopup">取消</view>
					<view class="popup-btn confirm" @click="confirmAddress">确定</view>
				</view>
			</view>
		</view>

		<!-- 调试信息（开发时可显示） -->
		<view class="debug-info" v-if="false">
			<text>登录状态: {{ isLoggedIn }}</text>
			<text>用户信息: {{ JSON.stringify(userInfo) }}</text>
			<text>Token: {{ token }}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartItems: [], // 购物车商品
				selectedAddress: "北京市海淀区中关村大街1号", // 默认地址
				notes: "", // 备注信息
				isLoggedIn: false, // 登录状态
				userInfo: {}, // 用户信息
				token: "", // token
				showAddressDialog: false, // 是否显示地址弹窗
				addressInput: "" // 地址输入内容
			}
		},
		computed: {
			// 计算总数量
			totalQuantity() {
				return this.cartItems.reduce((total, item) => total + item.quantity, 0)
			},
			// 计算总价
			totalPrice() {
				return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
			}
		},
		methods: {
			// 显示地址选择弹窗
			showAddressPopup() {
				this.addressInput = this.selectedAddress || "";
				this.showAddressDialog = true;
			},

			// 关闭地址选择弹窗
			closeAddressPopup() {
				this.showAddressDialog = false;
			},

			// 确认地址选择
			confirmAddress() {
				if (this.addressInput.trim()) {
					this.selectedAddress = this.addressInput.trim();
					// 保存到本地存储
					try {
						uni.setStorageSync('selectedAddress', this.selectedAddress);
					} catch (error) {
						console.error('保存地址出错:', error);
					}
					this.closeAddressPopup();
				} else {
					uni.showToast({
						title: '请输入有效地址',
						icon: 'none'
					});
				}
			},

			// 加载保存的地址
			loadSavedAddress() {
				try {
					const savedAddress = uni.getStorageSync('selectedAddress');
					if (savedAddress) {
						this.selectedAddress = savedAddress;
					}
				} catch (error) {
					console.error('加载地址出错:', error);
				}
			},

			// 检查登录状态
			checkLogin() {
				try {
					// 从存储中获取用户信息和token
					const userInfo = uni.getStorageSync('userInfo')
					const token = uni.getStorageSync('token')

					console.log('检查登录状态:', {
						userInfo,
						token
					})

					// 判断是否登录的条件 - 修改为只需要用户信息即可
					const isUserLoggedIn = userInfo && typeof userInfo === 'object' &&
						Object.keys(userInfo).length > 0 &&
						userInfo.username

					this.isLoggedIn = isUserLoggedIn
					this.userInfo = userInfo || {}
					this.token = token || ""

					console.log('登录状态结果:', this.isLoggedIn)
					return this.isLoggedIn
				} catch (error) {
					console.error('检查登录状态出错:', error)
					this.isLoggedIn = false
					return false
				}
			},

			// 提交订单前的登录检查
			checkLoginBeforeSubmit() {
				const isLoggedIn = this.checkLogin()
				console.log('提交前登录检查:', isLoggedIn)

				if (!isLoggedIn) {
					uni.showModal({
						title: '请先登录',
						content: '您需要登录后才能提交订单',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.navigateToLogin()
							}
						}
					})
					return false
				}

				// 检查是否选择了地址
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
					return false
				}

				this.submitOrder()
			},

			// 跳转到登录页面
			navigateToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},

			async request(url, method = 'GET', data = {}) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:8080' + url,
						method,
						data,
						header: {
							'Content-Type': 'application/json',
							'Authorization': this.token ? `Bearer ${this.token}` : ''
						},
						success: (res) => {
							resolve(res.data)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},

			// 加载购物车数据
			loadCartFromStorage() {
				try {
					const savedCart = uni.getStorageSync('cartItems')
					if (savedCart) {
						this.cartItems = savedCart
					}
				} catch (error) {
					console.error('加载购物车数据出错:', error)
				}
			},

			// 增加商品数量
			increase(item) {
				item.quantity++
				this.saveCartToStorage()
				this.updateClassifyPage()
			},

			// 减少商品数量
			decrease(item) {
				if (item.quantity > 1) {
					item.quantity--
				} else {
					// 移除数量为0的商品
					const index = this.cartItems.findIndex(i => i.id === item.id)
					if (index !== -1) {
						this.cartItems.splice(index, 1)
					}
				}
				this.saveCartToStorage()
				this.updateClassifyPage()
			},

			// 保存购物车到本地存储
			saveCartToStorage() {
				try {
					uni.setStorageSync('cartItems', this.cartItems)
				} catch (error) {
					console.error('保存购物车数据出错:', error)
				}
			},

			// 更新分类页面的购物车数据
			updateClassifyPage() {
				try {
					const pages = getCurrentPages()
					const classifyPage = pages.find(page => page.route === 'pages/classify/classify')
					if (classifyPage && classifyPage.$vm && classifyPage.$vm.loadCartFromStorage) {
						classifyPage.$vm.loadCartFromStorage()
					}
				} catch (error) {
					console.error('更新分类页面出错:', error)
				}
			},

			// 提交订单
			async submitOrder() {
				// 再次检查登录状态
				if (!this.checkLogin()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}

				// 构建订单数据
				const orderData = {
					address: this.selectedAddress,
					userId: this.userInfo.id || this.userInfo.userId,
					notes: this.notes,
					items: this.cartItems.map(item => ({
						dishId: item.id,
						quantity: item.quantity,
						price: item.price,
						name: item.name,
						totalPrice: (item.price * item.quantity).toFixed(2)
					})),
					totalAmount: this.totalPrice.toFixed(2),
					totalQuantity: this.totalQuantity
				}

				console.log('提交订单数据:', orderData)

				try {
					const res = await this.request('/t-order/saveOrder', 'POST', orderData)

					if (res.code === 200) {
						uni.showModal({
							title: '提交成功',
							content: '订单已成功提交',
							showCancel: false,
							success: () => {
								// 清空购物车
								this.clearCart()
							}
						})
					} else {
						uni.showToast({
							title: '提交失败: ' + (res.message || '未知错误'),
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('提交订单出错:', error)
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				}
			},

			// 清空购物车
			clearCart() {
				this.cartItems = []
				this.saveCartToStorage()
				this.updateClassifyPage()
			},

			// 去选购
			goToClassify() {
				uni.switchTab({
					url: '/pages/classify/classify'
				})
			}
		},
		onLoad() {
			this.loadCartFromStorage()
			this.checkLogin()
			this.loadSavedAddress()
		},
		onShow() {
			this.loadCartFromStorage()
			this.checkLogin()
		}
	}
</script>

<style lang="scss" scoped>
	.cart-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.nav-bar {
		height: 88rpx;
		display: flex;
		align-items: center;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
		position: relative;

		.nav-back {
			position: absolute;
			left: 20rpx;
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.back-icon {
				font-size: 48rpx;
				font-weight: bold;
			}
		}

		.nav-title {
			font-size: 36rpx;
			font-weight: bold;
			text-align: center;
			flex: 1;
		}
	}

	.cart-content {
		flex: 1;
		padding: 20rpx;
	}

	.address-section {
		display: flex;
		align-items: center;
		padding: 30rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;

		.address-info,
		.address-placeholder {
			flex: 1;

			.label {
				font-weight: bold;
				margin-right: 10rpx;
			}

			.address {
				color: #666;
			}
		}

		.arrow {
			font-size: 48rpx;
			color: #999;
		}
	}

	.dish-list {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
	}

	.cart-item {
		display: flex;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}

		.item-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 12rpx;
			margin-right: 20rpx;
		}

		.item-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			overflow: hidden;

			.item-name {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
			}

			.item-desc {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 20rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.item-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.item-price {
					font-size: 36rpx;
					color: #e74c3c;
					font-weight: bold;
				}

				.cart-control {
					display: flex;
					align-items: center;
					gap: 20rpx;

					.control-btn {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
						background-color: #f0f0f0;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 36rpx;
						font-weight: bold;

						&.plus {
							background-color: #e74c3c;
							color: #fff;
						}

						&.minus {
							color: #666;
						}

						&.disabled {
							opacity: 0.5;
						}
					}

					.quantity {
						font-size: 32rpx;
						font-weight: bold;
						min-width: 60rpx;
						text-align: center;
					}
				}
			}
		}
	}

	.order-summary {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;

		.summary-item {
			display: flex;
			justify-content: space-between;
			margin-bottom: 15rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.summary-label {
				font-size: 28rpx;
				color: #666;
			}

			.summary-value {
				font-size: 28rpx;
				font-weight: bold;
				color: #e74c3c;
			}
		}
	}

	.notes-section {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 16rpx;

		.section-title {
			display: block;
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.notes-input {
			width: 100%;
			height: 120rpx;
			background-color: #f8f8f8;
			padding: 20rpx;
			border-radius: 12rpx;
			box-sizing: border-box;
		}
	}

	.empty-cart {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 40rpx;
		}

		.empty-text {
			font-size: 32rpx;
			color: #999;
			margin-bottom: 40rpx;
		}

		.go-shopping {
			background-color: #e74c3c;
			color: #fff;
			padding: 20rpx 60rpx;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.checkout-bar {
		height: 100rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		align-items: center;
		padding: 0 20rpx;

		.total-info {
			flex: 1;

			.total-label {
				font-size: 32rpx;
				color: #333;
			}

			.total-price {
				font-size: 36rpx;
				color: #e74c3c;
				font-weight: bold;
			}
		}

		.checkout-btn {
			background-color: #e74c3c;
			color: #fff;
			padding: 20rpx 40rpx;
			border-radius: 40rpx;
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.address-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;

		.popup-mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.popup-content {
			position: relative;
			width: 80%;
			max-width: 600rpx;
			background-color: #fff;
			border-radius: 20rpx;
			overflow: hidden;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);

			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #f0f0f0;

				.popup-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}

				.popup-close {
					font-size: 40rpx;
					color: #999;
					width: 50rpx;
					height: 50rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.address-input-section {
				padding: 30rpx;

				.address-input {
					width: 100%;
					min-height: 150rpx;
					padding: 20rpx;
					background-color: #f8f8f8;
					border-radius: 12rpx;
					font-size: 28rpx;
					line-height: 1.5;
					box-sizing: border-box;
					border: 1rpx solid #e0e0e0;

					&:focus {
						border-color: #e74c3c;
					}
				}
			}

			.popup-buttons {
				display: flex;
				border-top: 1rpx solid #f0f0f0;

				.popup-btn {
					flex: 1;
					height: 90rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;
					font-weight: bold;

					&.cancel {
						color: #666;
						background-color: #f8f8f8;
						border-right: 1rpx solid #f0f0f0;
					}

					&.confirm {
						color: #fff;
						background-color: #e74c3c;
					}
				}
			}
		}
	}
</style>